package com.ignou.mca.evote;

import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import com.ignou.mca.beans.CastVoteFormBean;
import com.ignou.mca.datasource.DataBaseUtilities;
import com.ignou.mca.util.SessionUtil;
import org.apache.log4j.Logger;

public class Vote extends HttpServlet implements Servlet {

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		Collection<CastVoteFormBean> vote = (ArrayList<CastVoteFormBean>)  session.getAttribute("CastedVotes");
		
		DataBaseUtilities dbu = new DataBaseUtilities();
		Connection con = dbu.getConnection();
		String query = "insert into votedetails (partyID,PositionID,UserID) values (?,?,?)";
		PreparedStatement pstmt;
		
		int doneVoting=0;
		if (!SessionUtil.validateSession(req, resp)) {
			resp.sendRedirect(req.getServletPath()+ "/Login.jsp");
			return;
		}
		
		try {
			
			Iterator<CastVoteFormBean> it = vote.iterator();
			while (it.hasNext()) {
				CastVoteFormBean castedVote = (CastVoteFormBean) it.next();
				 pstmt = con.prepareStatement(query);
				 pstmt.setInt(1,castedVote.getPartyID() );
				 pstmt.setInt(2,castedVote.getPositionID());
				 pstmt.setString(3, castedVote.getUserName());
				 int i = pstmt.executeUpdate();
				 if(i==1)
				 {
					 doneVoting++; 
				 }
					 
			}
			
			ServletContext context = getServletContext();
			
			if(vote.size()==doneVoting)
			{
				context.getRequestDispatcher("/ThankYou.jsp").forward(req,resp);
			}
			else
			{
				context.getRequestDispatcher("/TransactionFailed.jsp").forward(req,resp);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

	}
}